﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using System.Speech.Synthesis;
using System.Speech.AudioFormat;

namespace WebApptest.Pages
{
    public class IndexModel : PageModel
    {

        private readonly IHostingEnvironment _IhostingEnvironment;
        [BindProperty(SupportsGet = true)]
        public string? Speektext { get; set; }
        public string filename { get; set; }
        public IndexModel(IHostingEnvironment hostingEnvironment)
        {
            _IhostingEnvironment= hostingEnvironment;
        }

        public async Task OnGetAsync()
        {
            string wavname = "test";
            string filePath = _IhostingEnvironment.WebRootPath+ $"\\speech\\{wavname}.wav";
            bool isFile = System.IO.File.Exists(filePath);
            if (isFile)
            {
                // 删除文件
                System.IO.File.Delete(filePath);
            }
            if (string.IsNullOrEmpty(Speektext))
                Speektext = "你好！欢迎关注“dotnet开发跳槽！”";
            if (!string.IsNullOrEmpty(Speektext))
            {
                using (SpeechSynthesizer synth = new SpeechSynthesizer())
                {
                    synth.SetOutputToWaveFile(filePath, new SpeechAudioFormatInfo(32000, AudioBitsPerSample.Sixteen, AudioChannel.Mono));
                    PromptBuilder builder = new PromptBuilder();
                    builder.AppendText(Speektext);
                    synth.Speak(builder);
                }
                filename =  $"\\speech\\{wavname}.wav";
            }
        }
    }
}
